import DexieCtx from '@/utils/dexiectx';
import Config from '@/utils/config';
import { Api, TelegramClient } from 'telegram'
import { StringSession } from 'telegram/sessions'

class PiggyTgweb {
  constructor() {
  }

  async allRun() {
    this.dexie = await DexieCtx.db()
    const allAccounts = await this.dexie.accounts.where("session").notEqual("").toArray()

    let sepIndex = 0;
    const groupStep = 10
    while (true) {
      if (sepIndex >= allAccounts.length) {
        break;
      }
      const start = sepIndex
      const end = Math.min(sepIndex + groupStep, allAccounts.length)
      const accountsGroup = allAccounts.slice(start, end)
      try {
        const allClients = accountsGroup.map(item => {
          const strSession = new StringSession(item.session)
          const client = new TelegramClient(strSession, Config.API_ID, Config.API_HASH, {
            connectionRetries: 3,
            useWSS: true,
            timeout: 20,
          })
          client.phone = item.phone
          return client
        })
        const promiseGroup = allClients.map(client => {
          return this.run(client)
        })
        await Promise.allSettled(promiseGroup)
        console.log(Date() + "piggy tgweb finished " + start + "~" + end)
      } catch (error) {
        console.error(error)
      } finally {
        sepIndex = end
      }
    }
  }

  async run(client) {
    try {
      await client.connect();
      const isAuth = await client.checkAuthorization()
      if (isAuth != true) {
        throw new Error("unauth");
      }
      const user = await client.getInputEntity('PiggyPiggyofficialbot');
      const result = await client.invoke(
        new Api.messages.RequestWebView({
          peer: user,
          bot: "PiggyPiggyofficialbot",
          fromBotMenu: true,
          url: "https://t.me/PiggyPiggyofficialbot/game?startapp=share_6162453001",
          platform: "ios"
        })
      );

      const url = result.url;
      await this.updatePiggyTable(client.phone, url)
    } catch (error) {
      console.error(client.phone, error)
      // if (error.message == 'unauth') {
      //   console.error(client.phone, "TG未登录")
      //   await dexie.piggy.where('phone').equals(client.phone).delete()
      //   await dexie.accounts.where('phone').equals(client.phone).modify({
      //     session: null
      //   })
      // }
    } finally {
      try {
        await client.disconnect()
        await client.destroy()
      } catch (error) {
      }
    }

  }

  async updatePiggyTable(phone, tgweb) {
    const oldValue = await this.dexie.piggy.get({
      phone: phone
    })
    const dateStr = (new Date()).toLocaleString()
    if (oldValue == null) {
      await this.dexie.piggy.add({
        phone,
        tgweb: tgweb,
        tokenupdate: dateStr,
      })
    } else {
      await this.dexie.piggy.where("phone").equals(phone).modify({
        tgweb: tgweb,
        tokenupdate: dateStr,
      })
    }
  }
}

export default PiggyTgweb